package com.springcloud.alibaba.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author:RenPu
 * @Date: 2020/7/1 9:53
 * @Version: 1.0
 * @description:
 */

@Service
public class PaymentServiceHystrix {

    /**
     * 此方法肯定成功
     * @param id
     * @return
     */

    @HystrixCommand(fallbackMethod = "asynMenthodFallBackF",commandProperties = {
            @HystrixProperty( name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String test_OK(Long id){
        int timeOut=10;
        try {
            TimeUnit.SECONDS.sleep(timeOut);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return  "线程池："+ Thread.currentThread().getName()+"*********"+id+"操作成功O(∩_∩)O哈哈~";

    }


    //降级方法的实现
    public String asynMenthodFallBackF(Long id){
        return "系统繁忙，o(╥﹏╥)o，请稍后再试o(╥﹏╥)oo(╥﹏╥)oo(╥﹏╥)oo(╥﹏╥)o，**************努力恢复中,id"+id;
    }


    /**
     * 模拟异常发生，让服务降级
     *
     * @param id
     * @return
     */
    public String test_ERROR(Long id){

        int timeOut=3;
        try {
            TimeUnit.SECONDS.sleep(timeOut);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池："+ Thread.currentThread().getName()+ id +"操作延时了o(╥﹏╥)o";

    }


    /**
     * 设置熔断的参数配置
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "asynMenthodFallBack",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //求情次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //请求窗口期，时间范围,10次请求在10000时间里，如果有百分之60的操作失败就进行熔断
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60") //失败率
    })
    public String test_RONGDUAN(Integer id){
        if(id<0){
                throw new RuntimeException(  "******** id不能为负数");
        }

       String number= IdUtil.simpleUUID();
        return "线程池："+ Thread.currentThread().getName()+ id +"调用成功，流水账号为："+number;

    }



    //降级方法的实现
    public String asynMenthodFallBack(Integer id){
        return "id不能为负数，o(╥﹏╥)o，请稍后再试o(╥﹏╥)oo(╥﹏╥)oo(╥﹏╥)oo(╥﹏╥)o，**************努力恢复中,id"+id;
    }



}
